﻿using System;
using System.Configuration;

namespace PKTools
{
    public class Stoper : IDisposable
    {
        readonly static int
            threshold;
        readonly DateTime
            start;

        readonly string
            stoperID;
        readonly Func<string>
            onStopF;

        static Stoper()
        {
            threshold = ConfigurationSettings.AppSettings["PKTools.Stoper.Threshold"].SafeToInt(100);

            Log.Entry(LogSeverity.Info, "stoper init, threshold {0} [ms]", threshold);
        }

        public Stoper(string stoperID, Func<string> onStopF = null)
        {
            this.stoperID = stoperID;
            this.onStopF = onStopF;

            this.start = DateTime.Now;
        }

        public int T
        {
            get { return (int)(DateTime.Now - this.start).TotalMilliseconds; }
        }

        public void Dispose()
        {
            int
                t = this.T;

            if (t > threshold || Log.Level == (int)LogSeverity.Debug)
                Log.Entry(LogSeverity.Info, "stoper {0} took {1} ms. " + (onStopF == null ? string.Empty : onStopF()), this.stoperID, t);
        }
    }
}
